import React, { useEffect, useState, useImperativeHandle } from 'react'
import { Form, Input, Select, Button, DatePicker } from 'antd'
import './index.styl'
import useForm from 'rc-form-hooks'
import moment from 'moment'
import { connect } from 'dva'
const { Option } = Select

function HeaderSearch({ cRef, dispatch, deviceUpkeep: { parameter }, handleQuery, status, today }) {
  const { getFieldDecorator, validateFields, values, resetFields, setFieldsValue, getFieldsValue } = useForm()
  useImperativeHandle(cRef, () => ({
    getFieldsValue,
    resetFields
  }));
  useEffect(() => {
    dispatch({
      type: 'deviceUpkeep/getQueryParameter'
    })
    if (status !== '') {
      resetFields()
      setFieldsValue({ status: status * 1 })
    }
    if (today !== '' && status !== '') {
      resetFields()
      setFieldsValue({
        status: status * 1,
        startTime: moment(moment(new Date()).format('YYYY-MM-DD')),
        endTime: moment(moment(new Date()).format('YYYY-MM-DD'))
      })
    }
  }, [dispatch, resetFields, setFieldsValue, status, today])

  // 表单提交
  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields()
      .then(() => {
        handleQuery(values)
      })
      .catch(e => console.error(e.message));
  }

  // 开始时间
  const [startTime, setStartTime] = useState()
  // 结束时间
  const [endTime, setEndTime] = useState()

  // 重置
  const onReset = () => {
    setStartTime()
    setEndTime()
    resetFields();
    dispatch({
      type: 'deviceUpkeep/updateSerachParams',
      payload: {
        serachParams: {
          current: 1
        }
      }
    });
  }

  // 开始时间
  const selectStartTime = (time, str) => {
    setStartTime(time)
  }

  // 开始时间
  const selectEndTime = (time, str) => {
    setEndTime(time)
  }

  // 设置开始不能选择的时间
  const disabledStartDate = startTime => {
    if (!startTime || !endTime) {
      return false
    }
    return startTime.valueOf() > endTime.valueOf()
  }

  //设置结束不能选择的时间
  const disabledEndDate = endTime => {
    if (!endTime || !startTime) {
      return false
    }
    return endTime.valueOf() <= startTime.valueOf()
  }

  return (
    <div className="deviceUpkeep_headerSearch">
      <Form name="nest-messages" className="self-form" onSubmit={handleSubmit}>
        <div className="flex flex1">
          <Form.Item label="计划名称" colon={false}>
            {getFieldDecorator('name', {
              initialValue: '',
              rules: [{ required: false, message: '' }],
            })(
              <Input className="self-input" placeholder="请输入" />
            )}
          </Form.Item>
          <Form.Item label="设备名称" colon={false}>
            {getFieldDecorator('deviceName', {
              initialValue: '',
              rules: [{ required: false, message: '' }],
            })(
              <Input className="self-input" placeholder="请输入" />
            )}
          </Form.Item>
          <Form.Item label="设备使用部门" colon={false}>
            {getFieldDecorator('groupName', {
              initialValue: '',
              rules: [{ required: false, message: '' }],
            })(
              <Input className="self-input" placeholder="请输入" />
            )}
          </Form.Item>
          <Form.Item label="保养员" colon={false}>
            {getFieldDecorator('maintainUserName', {
              initialValue: '',
              rules: [{ required: false, message: '' }],
            })(
              <Input className="self-input" placeholder="请输入" />
            )}
          </Form.Item>
          <Form.Item label="保养类型" colon={false}>
            {getFieldDecorator('type', {
              rules: [{ required: false, message: '' }],
            })(
              <Select
                placeholder="请选择"
                className="self-select"
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {
                  parameter
                  && JSON.stringify(parameter) !== '{}'
                  && parameter.maintainTypeList
                  && parameter.maintainTypeList.length > 0
                  && parameter.maintainTypeList.map(item => {
                    return (
                      <Option value={item.code} key={item.code}>{item.desc}</Option>
                    )
                  })
                }
              </Select>
            )}
          </Form.Item>
        </div>
        <div className="flex">
          <Form.Item label="保养级别" colon={false}>
            {getFieldDecorator('level', {
              rules: [{ required: false, message: '' }],
            })(
              <Select
                placeholder="请选择"
                className="self-select"
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {
                  parameter
                  && JSON.stringify(parameter) !== '{}'
                  && parameter.maintainLevelList
                  && parameter.maintainLevelList.length > 0
                  && parameter.maintainLevelList.map(item => {
                    return (
                      <Option value={item.code} key={item.code}>{item.desc}</Option>
                    )
                  })
                }
              </Select>
            )}
          </Form.Item>
          <Form.Item label="计划状态" colon={false}>
            {getFieldDecorator('status', {
              rules: [{ required: false, message: '' }],
            })(
              <Select
                placeholder="请选择"
                className="self-select"
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {
                  parameter
                  && JSON.stringify(parameter) !== '{}'
                  && parameter.planStatusList
                  && parameter.planStatusList.length > 0
                  && parameter.planStatusList.map(item => {
                    return (
                      <Option value={item.code} key={item.code}>{item.desc}</Option>
                    )
                  })
                }
              </Select>
            )}
          </Form.Item>
          <Form.Item label="最近执行时间" colon={false}>
            {getFieldDecorator('startTime', {
              initialValue: null,
              rules: [{ required: false, message: '' }],
            })(
              <DatePicker
                className="self-date"
                showToday={false}
                placeholder="选择结束时间"
                onChange={selectStartTime}
                disabledDate={disabledStartDate}
              />
            )}
          </Form.Item>
          <Form.Item label="">
            {getFieldDecorator('endTime', {
              initialValue: null,
              rules: [{ required: false, message: '' }],
            })(
              <DatePicker
                className="self-date"
                showToday={false}
                placeholder="选择结束时间"
                disabledDate={disabledEndDate}
                onChange={selectEndTime}
              />
            )}
          </Form.Item>
          <Button className="blue-button btn_styls" htmlType="submit">查询</Button>
          <Button className="white-button" onClick={onReset}>重置</Button>
        </div>
      </Form>
    </div>
  )
}
export default connect(({ deviceUpkeep }) => ({
  deviceUpkeep
}))(HeaderSearch)
